package com.heng.futureDemo;

import lombok.Getter;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

public class ACompletableFutureBuildDemo8 {
    static List<NetMall> list = Arrays.asList(
            new NetMall("jd"),
            new NetMall("dangdang"),
            new NetMall("taobao"),
            new NetMall("pdd"),
            new NetMall("tmall")
    );

    public static List<String> getPrice(List<NetMall> list,String productName){
        return list
                .stream().
                map(netMall -> String.format(productName+" in %s price is %.2f"
                        ,netMall.getNetMallName()
                        ,netMall.calcPrice(productName)))
                .collect(Collectors.toList());
    }

    //从功能到性能的改进！
    public static List<String> getPriceByCompletableFuture(List<NetMall> list,String productName){
         return list.stream().map(netMall ->
                 CompletableFuture.supplyAsync(() -> String.format(productName+" in %s price is %.2f",
                         netMall.getNetMallName(),
                         netMall.calcPrice(productName))))
                 .collect(Collectors.toList())
                 .stream()
                 .map(s -> s.join())
                 .collect(Collectors.toList());
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        List<String> lis = getPrice(list,"mysql");
        for (String element : lis) {
            System.out.println(element);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("---costTime: " + (endTime - startTime) + "毫秒");

        System.out.println("========================================================");

        startTime = System.currentTimeMillis();
        List<String> list1 = getPriceByCompletableFuture(list,"mysql");
        for (String element : list1) {
            System.out.println(element);
        }
        endTime = System.currentTimeMillis();
        System.out.println("---costTime: " + (endTime - startTime) + "毫秒");
    }
}

class NetMall{
    @Getter
    private String netMallName;
    public NetMall(String netMallName) {
        this.netMallName = netMallName;
    }
    public double calcPrice(String productName) {
        try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }
}